package com.jingdianjichi.auth.domain.service.impl;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.jingdianjichi.auth.common.enums.IsDeletedFlagEnum;
import com.jingdianjichi.auth.domain.convert.AuthPermissionConverter;
import com.jingdianjichi.auth.domain.entity.AuthPermissionBO;
import com.jingdianjichi.auth.domain.redis.RedisUtil;
import com.jingdianjichi.auth.domain.service.AuthPermissionDomainService;
import com.jingdianjichi.auth.infra.basic.entity.AuthPermission;
import com.jingdianjichi.auth.infra.basic.service.AuthPermissionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AuthPermissionDomainServiceImpl implements AuthPermissionDomainService {

    @Resource
    private AuthPermissionService permissionService;

    //用工具类去交互
    @Resource
    private RedisUtil redisUtil;

    //权限,我们是隔离的这两个,我们在存入Redis的时候也要这样存储的
    private String authPermissionPrefix="auth.permission";

    //角色
    //新增
    @Override
    public Boolean add(AuthPermissionBO permissionBO) {
        AuthPermission permission=AuthPermissionConverter.INSTANCE.convertBOtoEntity(permissionBO);
        permission.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());

        Integer count = permissionService.insert(permission);


        return count>0;
    }

    //修改权限
    @Override
    public Boolean update(AuthPermissionBO permissionBO) {
        AuthPermission permission=AuthPermissionConverter.INSTANCE.convertBOtoEntity(permissionBO);

        Integer count = permissionService.update(permission);

        return count>0;
    }

    //删除权限
    @Override
    public Boolean delete(AuthPermissionBO permissionBO) {
        AuthPermission permission = new AuthPermission();
        permission.setId(permissionBO.getId());
        permission.setIsDeleted(IsDeletedFlagEnum.DELETED.getCode());

        Integer count = permissionService.update(permission);

        return count>0;
    }

    //我们用户的所有权限都在Redis中的,我们直接交互就行了
    @Override
    public List<String> getPermission(String userName) {
        String permissionKey = redisUtil.buildKey(authPermissionPrefix, userName);

        String permissionValue = redisUtil.get(permissionKey);

        //返回空的
        if (StringUtils.isBlank(permissionValue)){
            return Collections.emptyList();
        }

        //如果不是空的话我们就要做序列化了
        List<AuthPermission> permissionList = new Gson().fromJson(permissionValue, new TypeToken<List<AuthPermission>>(){}.getType());

        List<String> authList=permissionList.stream().map(AuthPermission::getPermissionKey).collect(Collectors.toList());

        return authList;
    }
}
